<template>
  <!-- 登录框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mark" @click="showModalFn(false)"></div>
    <!-- 登录盒子 -->
    <div class="loginbox">
      <div class="close" @click="showModalFn(false)"></div>
      <!-- 导航 -->
      <div class="nav">
        <a
          href="#"
          :class="[isShowContent ? 'active' : '']"
          @click="isShowContent = true"
          >手机号码登录</a
        >
        |
        <a
          href="#"
          :class="[!isShowContent ? 'active' : '']"
          @click="showQrCode"
          >微信扫码登录</a
        >
      </div>
      <!-- 导航对应的盒子内容 -->
      <div class="content">
        <!-- 手机号码登录 -->
        <div class="phonelogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <!-- 滑块 -->
          <div class="row">
            <!-- <input type="text" placeholder="向右滑动填充拼图" /> -->
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imgs"
            ></slide-verify>
          </div>
          <!-- 验证码 -->
          <div class="row">
            <input
              class="ipt"
              type="text"
              placeholder="请输入短信验证码"
              v-model="phoneCode"
            />
            <button class="btncode btn" @click="getCode" v-show="isShowCount">
              获取验证码
            </button>
            <button class="btncode btn" v-show="!isShowCount">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="loginbtn btn" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信二维码登录 -->
        <div class="qrLogin" id="weixin" v-show="!isShowContent"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from "vuex";
import { validateTelephoneNumber } from "../utils";
import {
  SendSMSAPI,
  PhoneReginAPI,
  BindPhoneAPI,
  UserProfilesAPI,
} from "../request/api";
export default {
  data() {
    return {
      // 显示内容盒子
      isShowContent: true,
      // 滑块提示信息
      msg: "向右滑动",
      // 自定义滑块图片
      imgs: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
      ],
      // 手机号码
      phoneNumber: "",
      // 倒计时数字
      count: 5,
      // 显示验证码盒子的内容
      isShowCount: true,
      // 短信验证码
      phoneCode: "",
    };
  },
  computed: {
    ...mapState({
      isShowModal: (state) => state.showModal.isShowModal,
    }),
  },
  methods: {
    ...mapMutations({
      // 控制登录模态框
      showModalFn: "showModal/showModalFn",
      // 显示购物车
      changeIsLogined: "loginStatus/changeIsLogined",
      // 提示组件
      changeShowToast: "showToast/changeShowToast",
    }),
    ...mapActions({
      asyncChangeToast: "showToast/asyncChangeToast",
      // 修改用户信息
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 判断函数
    toVerify() {
      // 1-判断手机号码格式是否正确，不正确，提示
      if (!validateTelephoneNumber(this.phoneNumber.trim())) {
        // alert("请输入正确的手机号码");
        this.asyncChangeToast({
          isShow: true,
          title: "请输入正确的手机号码",
          type: "error",
        });
        this.phoneNumber = "";
        return;
      }
      // 2-判断滑块是否成功 不正确，提示
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        this.asyncChangeToast({
          isShow: true,
          title: "请重新滑动滑块验证码",
          type: "error",
        });
        return;
      }
      // 函数要有返回值
      return true;
    },
    // 判断验证码
    async getCode() {
      let flag = this.toVerify();
      if (!flag) return;
      // 3-开始获取验证码(请求后发送验证码)，发送成功后，进行倒计时请求
      let res = await SendSMSAPI({
        phone: this.phoneNumber.trim(),
      });
      if (!res) return false;
      this.isShowCount = false;
      let timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          clearInterval(timer);
          this.count = 5;
          this.isShowCount = true;
        }
      }, 1000);
      /*
         解决连续点击bug
         原因：连续点频繁触发@click,只需要触发一次
         解决：添加多一个按钮显示数字
      */
    },
    // 登录
    async submitFn() {
      if (!this.toVerify()) return;
      // alert("验证成功");
      if (!this.phoneCode.trim()) {
        this.asyncChangeToast({
          type: "warning",
          title: "请输入短信验证",
          isShow: true,
        });
        return;
      }
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        // 有uuid 手机绑定微信登录
        res = await BindPhoneAPI({
          verifyCode: this.phoneCode,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        // 普通手机号登录
        res = await PhoneReginAPI({
          verifyCode: this.phoneCode,
          phone: this.phoneNumber,
        });
      }
      if (!res) return;
      if (res.code == 0) {
        // 1-提示登录成功
        this.asyncChangeToast({
          isShow: true,
          title: "手机号码登录成功",
          type: "success",
        });
        // 2-存储token
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        // 3-隐藏登录框
        this.showModalFn(false);
        // 4-更新登录状态(已登录--购物车，没登陆--登录按钮)
        this.changeIsLogined(true);
        // 5-清除uuid，用过就不需要绑定了
        localStorage.removeItem("uuid");
        // (绑定成功后，提示信息会与普通登录不同)下一次扫码就不会出现407，会直接0
        // 登录成功，发送用户信息请求
        // 修改用户信息
        this.asyncChangeUserInfo();
      }
    },
    // 显示二维码
    showQrCode() {
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICBkaXNwbGF5OiBub25lOw0KfQ0KLmltcG93ZXJCb3ggcXJjb2RlIHsNCiAgbWFyZ2luLXRvcDogMjBweDsNCn0NCg==",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mark {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 60px;
      top: 16px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
    }
    .nav {
      margin-top: 45px;
      text-align: center;
      font-size: 18px;
      a {
        text-decoration: none;
        color: rgb(175, 174, 174);
        &.active {
          color: black;
        }
      }
    }
    .content {
      width: 355px;
      // background: pink;
      margin: 20px auto;
      .qrLogin {
        text-align: center;
      }
      .phonelogin {
        .row {
          display: flex;
          margin-bottom: 20px;

          input {
            flex: 1;
            height: 50px;
            outline: none;
            text-indent: 1em;
          }
          .btncode {
            width: 80px;
          }
          .ipt {
            margin-right: 10px;
            outline: none;
          }
          .loginbtn {
            height: 50px;
            width: 100%;
          }
          /deep/.slide-box {
            width: 100%;
            position: relative;
            box-sizing: border-box;
            canvas {
              position: absolute;
              left: 0;
              top: -120px;
              display: none;
              width: 100%;
              box-sizing: border-box;
            }
            .slide-verify-block {
              width: 85px;
              height: 136px;
            }
            .slide-verify-refresh-icon {
              top: -120px;
              display: none;
            }
            &:hover {
              canvas {
                display: block;
              }
              .slide-verify-refresh-icon {
                display: block;
              }
            }
          }
        }
        .btn {
          color: #fff;
          background-color: #0a328e;
          border: none;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
